package cn.dglydrpy.study.j2ee.servlet.day09;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * 将session验证写入过滤器中
 */
public class LoginFilter9 implements Filter {
	private List<String> filePath = new ArrayList<String>();//存放需要做session验证的配置文件中的地址
	

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		//获取请求资源路径：
		String URL = request.getRequestURI();

		//截取
		String path = URL.substring(URL.lastIndexOf("/"),URL.lastIndexOf("."));

		//依据请求路径，进行对应的处理：

		if (filePath.contains(path)) {//进行session验证后重定向到登录
			//session验证
			HttpSession session = request.getSession();
			Object object = session.getAttribute("user");
			if(object == null){
				response.sendRedirect("login.jsp");
				return;
			}
		} 
		arg2.doFilter(request, response);//走servlet（）
	}

	public void init(FilterConfig arg0) throws ServletException {
		String string = arg0.getInitParameter("path");
		String[] datas = string.split(",");
		for (String data : datas) {
			filePath.add(data);
		}
		System.out.println(filePath);
	}
}
